<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        .image-box {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .image-item {
            position: relative;
            width: 500px;
            height: 400px;
            margin: 20px;
            border: 1px solid #eee;
            padding: 10px;
            background-image: url('');
            background-repeat: repeat;
            background-color: #FFFFFF;
        }

        .image-item img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        .image-item .label {
            position: absolute;
            top: 0;
            right: 0;
            background-color: #ccc;
            padding: 4px 10px;
            font-size: 14px;
            color: #fff;
        }

        .image-input {
            display: block;
            width: 500px;
            height: 80px;
            margin: 20px;
        }
        #original-item {
            display: none;
        }
    </style>


</head>

<body>
    <div>
        <button onclick="changeInputType('local')">本地图片</button>
        <button onclick="changeInputType('input')">输入框</button>
    </div>
    <div style="display: flex; flex-direction: column; align-items: center; padding: 40px;">
        <input type="file" accpet="image/*" name="originalFile" id="originalFile">

        <div class="image-box" style="margin-top: 40px;">
            <div class="image-item" style="background-color: rgba(0, 0, 0, 0.05);" id="original-item">
                <img id="originalImage" src="" />
                <div class="label">原图(抠完的图)</div>
            </div>
            <input type="text" name="originalFile" class="image-input" id="imageInput">
            <div>
                <button onclick="toMaskData()">生成</button>
            </div>
            <div class="image-item">
                <img id="maskImage" src="" />
                <div class="label">Mask</div>
            </div>
        </div>
    </div>

    <script src="https://www.shuiyinyun.com/themes/shuiyinyun-v3/public/libs/jquery-1.11.1.min.js"></script>
    <script>
        var originalImage, originalWidth, originalHeight;
        var inputType = '';
        
        function changeInputType(type) {
            inputType = type
            if(inputType === 'input') {
                $("#imageInput").show()
                $("#original-item").hide()
            } else {
                $("#imageInput").hide()
                $("#original-item").show()
            }
        }

        changeInputType('input')

        $("#originalFile").change(function () {
            let files = $(this).prop('files');
            if (files[0]) {
                let tempFilePath = URL.createObjectURL(files[0])
                console.log(tempFilePath)
                loadImage(tempFilePath).then(image => {
                    changeInputType('local')
                    originalWidth = image.width;
                    originalHeight = image.height;
                    originalImage = image;
                    $('#originalImage').attr('src', tempFilePath)
                }).catch(err => {
                    console.log(err)
                })
            }
        })

        function loadImage(src) {
            return new Promise((resolve, reject) => {
                let image = new Image();
                image.setAttribute('crossOrigin', 'Anonymous');
                image.src = src;
                image.onload = function () {
                    resolve(image)
                };
                image.onerror = function (err) {
                    reject(err)
                };
            })
        }

        async function toMaskData() {
            if(inputType == 'input') {
                let inputUrl = $('#imageInput').val()
                let image = await loadImage(inputUrl).catch(err => {
                    console.log(err)
                    alert(err)
                })
                console.log(image)
                if(image) {
                    originalWidth = image.width;
                    originalHeight = image.height;
                    originalImage = image;
                    $('#originalImage').attr('src', inputUrl)
                } else {
                    return
                }
            }


            if (!originalImage) {
                return;
            }
            console.log('toMaskData')
            let originalCanvas = document.createElement('canvas'); // 用于绘制原始PNG图像
            let originalContext = originalCanvas.getContext('2d');

            let displayCanvas = document.createElement('canvas'); // 用于显示处理后的图像
            let displayContext = displayCanvas.getContext('2d');

            originalCanvas.width = originalWidth;
            originalCanvas.height = originalHeight;
            originalContext.drawImage(originalImage, 0, 0, originalWidth, originalHeight);

            // 在绘制前清空显示Canvas并填充为黑色
            displayCanvas.width = originalCanvas.width;
            displayCanvas.height = originalCanvas.height;
            displayContext.fillStyle = 'black';
            displayContext.fillRect(0, 0, displayCanvas.width, displayCanvas.height);

            // 获取原始Canvas上的图像像素数据，并遍历每个像素进行处理
            let imageData = originalContext.getImageData(0, 0, originalCanvas.width, originalCanvas.height);
            // let data = imageData.data;

            // for (let i = 0; i < data.length; i += 4) {
            //     let alpha = data[i + 3];

            //     if (alpha !== 0) {
            //         // 如果像素不是完全透明的
            //         data[i] = 255; // 设置红色通道为255（白色）
            //         data[i + 1] = 255; // 设置绿色通道为255（白色）
            //         data[i + 2] = 255; // 设置蓝色通道为255（白色）
            //     }
            // }

            originalContext.putImageData(imageData, 0, 0);

            // 将处理后的图像绘制到显示Canvas上
            displayContext.drawImage(originalCanvas, 0, 0);
            let maskBase64 = displayCanvas.toDataURL('image/png');

            $('#maskImage').attr('src', maskBase64)
        }
    </script>
</body>

</html>